import { generateReport, GenerateReportParams } from '@/common/api';
import RecordCountModal from '@/pages/family-counselor/record-count-modal';
import ReportGenerateModal from '@/pages/family-counselor/report-generate-modal';
import ReportListModal from '@/pages/family-counselor/report-list-modal';
import { FamilyInfo, FamilyListReqParam, familyUpdate, getFamilyList } from '@/services/family/api';
import { PageContainer, ProColumnType, ProTable } from '@ant-design/pro-components';
import { Button, Input, message } from 'antd';
import to from 'await-to-js';
import classNames from 'classnames';
import React, { useRef, useState } from 'react';

import ReportSettingModal from "@/pages/family-counselor/report-setting-modal";
import "./record-list.scss";

const RecordList: React.FC = () => {
  const [reportListModalVisible, setReportListModalVisible] = useState<boolean>(false);
  const [recordCountModalVisible, setRecordCountModalVisible] = useState<boolean>(false);
  const [currentReportGenerateFamilyId, setCurrentReportGenerateFamilyId] = useState<number>(0);

  const [reportGenerateModalVisible, setReportGenerateModalVisible] = useState<boolean>(false);
  const [reportSettingModalVisible, setReportSettingModalVisible] = useState<boolean>(false);
  const [currentReportFamilyInfo, setCurrentReportFamilyInfo] = useState<FamilyInfo>();
  const [familyList, setFamilyList] = useState<FamilyInfo[]>([]);
  const [params, setParams] = useState<any>( {
    current: 1,
    pageSize: 50,
  });

  const showReportGenerateModal = (familyId: number) => {
    setReportGenerateModalVisible(true);
    setCurrentReportGenerateFamilyId(familyId);
  };

  const showReportListModal = (familyInfo: FamilyInfo) => {
    setCurrentReportFamilyInfo(familyInfo);
    setReportListModalVisible(true);
  };
  const showRecordCountModal = (familyInfo: FamilyInfo) => {
    setCurrentReportFamilyInfo(familyInfo);
    setRecordCountModalVisible(true);
  };
  const showReportSettingModal = (familyInfo: FamilyInfo) => {
    setCurrentReportFamilyInfo(familyInfo);
    setReportSettingModalVisible(true);
  };

  const focusOrUnfocusFamily = async (familyInfo: FamilyInfo, focusStatus: number) => {
    const [err, res] = await to(familyUpdate({
      id: familyInfo.id,
      focus: focusStatus,
    }));
    if (err || !res) {
      message.error(`关注家庭${familyInfo.name}失败`);
      return;
    }
  };

  const columns: ProColumnType<FamilyInfo>[] = [
    {
      title: '重点关注',
      dataIndex: 'focus',
      key: 'focus',
      valueType: 'select',
      width: 80,
      fieldProps: {
        width: 30,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
      render(_text, record) {
        return (
          <Input
            type="checkbox"
            checked={record.focus}
            onChange={(e) => {
              const focusStatus = e.target.checked;
              record.focus = e.target.checked;
              setFamilyList(familyList.map((item) => {
                if (item.id === record.id) {
                  item.focus = focusStatus;
                }
                return item;
              }));
              focusOrUnfocusFamily(record, focusStatus ? 1 : 0)
            }}
          />
        );
      },
    },
    {
      title: '家庭名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render(_text, record) {
        return (
          <div className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            {_text}
          </div>
        );
      },
    },
    {
      title: '家庭码',
      dataIndex: 'code',
      key: 'code',
      render(_text, record) {
        return (
          <div className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            {_text}
          </div>
        );
      },
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
      valueType: 'dateRange',
      width: 200,
      render(_text, record) {
        return (
          <div className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            {record.createTime}
          </div>
        );
      }
    },
    {
      hideInSearch: true,
      title: '聊天记录总数',
      dataIndex: 'sessionCount',
      key: 'id',
      valueType: 'digitRange',
      width: 140,
      render(_text, record) {
        if(!record.sessionCount) {
          return <span>-</span>;
        }

        return (
          <div style={{display: 'flex', justifyContent: 'space-between'}} className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            <span>{record.sessionCount}&nbsp;</span>
            <Button size="small" type="primary" onClick={() => showRecordCountModal(record)}>查看报表</Button>
          </div>
        );
      },
    },
    {
      hideInSearch: true,
      title: '昨日聊天记录数',
      dataIndex: 'yesterdaySessionCount',
      key: 'id',
      width: 120,
      render(_text, record) {
        return (
          <div className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            {record.yesterdaySessionCount || 0}
          </div>
        );
      },
    },
    {
      title: '上次报告产生日期',
      dataIndex: 'lastReportTime',
      key: 'lastReportTime',
      valueType: 'dateRange',
      width: 240,
      render(_text, record): React.JSX.Element {
        if (!record.lastReportTime) {
          return <span>-</span>;
        }
        return (
          <div style={{display: 'flex', justifyContent: 'space-between'}} className={classNames({ 'less-than-30-warn': record.focus && record.yesterdaySessionCount < 30, })}>
            <span>{record.lastReportTime}&nbsp;</span>
            <Button size="small" type="primary" onClick={() => showReportListModal(record)}>查看报告</Button>
          </div>
        );
      },
    },
    {
      hideInSearch: true,
      title: '操作',
      dataIndex: 'lastReportTime',
      key: 'id',
      render(_text, record): React.JSX.Element {
        return (
          <>
            <Button
              size="small"
              type="primary"
              onClick={() => {
                showReportGenerateModal(record.id);
              }}
            >
              生成报告
            </Button>
            &nbsp;
            <Button size="small" type="primary" onClick={() => showReportSettingModal(record)}>设置</Button>
          </>
        );
      },
    },
  ];

  const handleReportGenerate = async (
    sessionStartTime: string,
    sessionEndTime: string,
    familyId: number,
    reportPrompt?: string,
  ) => {
    console.log(sessionStartTime, sessionEndTime);
    setReportGenerateModalVisible(false);
    const reqParams: GenerateReportParams = {
      startTime: sessionStartTime,
      endTime: sessionEndTime,
      familyId,
    };
    if (reportPrompt && reportPrompt.trim()) {
      reqParams.reportPrompt = reportPrompt;
    }
    message.info('正在生成报告，请稍候进行查看');
    const [err] = await to(generateReport(reqParams));
    if (err) {
      return;
    }
    return;
  };

  const tableRef = useRef<any>();

  return (
    <PageContainer
      header={{
        title: null,
      }}
      className="record-list-container"
    >
      <ProTable
        toolBarRender={false}
        actionRef={tableRef}
        defaultSize="small"
        rowKey={'id'}
        columns={columns}
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        params={params}
        // 第一个参数 params 查询表单和 params 参数的结合
        // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
        dataSource={familyList}
        request={async (params: FamilyListReqParam) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          if (params.lastReportTime) {
            params.lastReportStartDate = params.lastReportTime[0] + ' 00:00:00';
            params.lastReportEndDate = params.lastReportTime[1] + ' 23:59:59';
          }
          if (params.createTime) {
            params.createStartDate = params.createTime[0] + ' 00:00:00';
            params.createEndDate = params.createTime[1] + ' 23:59:59';
          }
          const [err, baseResponse] = await to(getFamilyList(params));
          if (err) {
            return {data: [], success: false};
          }

          setFamilyList(baseResponse?.result);

          return {data: baseResponse?.result, success: baseResponse?.code === '0'};
        }}
        search={{
          searchText: '搜索',
          labelWidth: 'auto',
          collapsed: false,
        }}
        debounceTime={100}
        // form={{
        //   onValuesChange: (_, values) => {
        //     setParams({
        //       ...params,
        //       ...values,
        //     });
        //     tableRef?.current.reload();
        //   },
        // }}
      />

      <ReportGenerateModal
        onOpenChange={setReportGenerateModalVisible}
        familyId={currentReportGenerateFamilyId}
        modalVisible={reportGenerateModalVisible}
        onSubmit={(sessionTimeArr, familyId, reportPrompt) => {
          const startTime = `${sessionTimeArr[0]} 00:00:00`;
          const endTime = `${sessionTimeArr[1]} 23:59:59`;
          handleReportGenerate(startTime, endTime, familyId, reportPrompt).then((r) => r);
        }}
      />

      <ReportSettingModal
        onOpenChange={setReportSettingModalVisible}
        onReportTypeSetSuccess={() => {
          tableRef.current.reload();
        }}
        familyInfo={currentReportFamilyInfo}
        modalVisible={reportSettingModalVisible}
      />

      <ReportListModal
        modalVisible={reportListModalVisible}
        onOpenChange={setReportListModalVisible}
        familyInfo={currentReportFamilyInfo}
      />

      <RecordCountModal
        modalVisible={recordCountModalVisible}
        onOpenChange={setRecordCountModalVisible}
        familyInfo={currentReportFamilyInfo}
      />
    </PageContainer>
  );
};

export default RecordList;
